package com.mida.app.knw.service.impl;

//import com.ats.mdm.auth.common.service.ILoginUserService;
//import com.ats.mdm.auth.common.vo.UserVo;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.mida.app.knw.service.DetailCodingSystemService;
import com.mida.app.knw.service.DtDefineSpaceService;
import com.mida.app.knw.service.MdmService;
import com.mida.dms.knw.api.DtDefineSpaceApi;
import com.mida.dms.knw.entity.DtDefineSpace;
import com.mida.dms.knw.entity.vo.DtDefineSpaceConsumerVo;
import com.mida.dms.knw.entity.vo.DtDefineSpaceVo;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.dms.mdm.dto.UserDto;
import com.mida.dms.mdm.pojo.auto.MsdDataSet;
import com.mida.dms.mdm.vo.provider.BaseOrgInfoVo;
import com.mida.dms.mdm.vo.provider.BusinessUnitVo;
import com.mida.dms.mdm.vo.provider.EmployeeInfoVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.ListResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.mida.tool.common.result.BaseResult.buildListSuccess;
import static com.mida.tool.common.result.BaseResult.buildListWarn;


/**
 * @author ：wang xiao le
 * @description：TODO
 * @date ：2021/3/22 16:34
 */
@Service
@Slf4j
public class DtDefineSpaceServiceIml implements DtDefineSpaceService {
    //    @Autowired
//    private ILoginUserService loginUserService;
    @Autowired
    private DtDefineSpaceApi dtDefineSpaceApi;
    @Autowired
    private MdmService mdmService;
    @Autowired
    private DetailCodingSystemService detailCodingSystemService;


    @Override
    public ActionResult add(DtDefineSpaceVo dtDefineSpaceVo) {
        return dtDefineSpaceApi.add(dtDefineSpaceVo);
    }

    @Override
    public ActionResult update(DtDefineSpaceVo dtDefineSpaceVo) {
        return dtDefineSpaceApi.update(dtDefineSpaceVo);
    }

    @Override
    public ActionResult delete(long defineSpaceSoid) {
        return dtDefineSpaceApi.delete(defineSpaceSoid);
    }


    @Override
    public ListResult<DtDefineSpaceVo> get(long defineSpaceSoid) {
        ListResult<DtDefineSpaceVo> lr = new ListResult<DtDefineSpaceVo>();
        try {
        ListResult<DtDefineSpaceVo> dtDefineSpaceVoListResult = dtDefineSpaceApi.get(defineSpaceSoid);
        if (ObjectUtils.isNotEmpty(dtDefineSpaceVoListResult)) {
            DtDefineSpaceVo dtDefineSpaceVo = dtDefineSpaceVoListResult.getData();
            List<DtDefineSpaceConsumerVo> dtDefineSpaceConsumerVos = dtDefineSpaceApi.getDtDefineSpaceVos(defineSpaceSoid);
            if (CollectionUtils.isNotEmpty(dtDefineSpaceConsumerVos)) {
                    dtDefineSpaceConsumerVos.stream().filter(vo->ObjectUtils.isNotEmpty(vo.getDoctorSoid())).forEach(consumer -> {
                        ListResult<EmployeeInfoVo> employee = mdmService.findOneBySoid(consumer.getDoctorSoid(), false);
                        //设置医生姓名
                        String doctorName = employee.getData().getEmployeeName();

                        //设置医生姓名与业务单元拼接的字段
                        ListResult<List<BusinessUnitVo>> unitList = mdmService.findBusinessUnitListByEmployeeSoid(consumer.getDoctorSoid(), null);
                        StringBuffer doctorNameWithUnitName = new StringBuffer(doctorName + "|");
                        List<BusinessUnitVo> data = unitList.getData();
                        for (int i = 0; i < data.size(); i++) {
                            if (i == data.size() - 1) {
                                doctorNameWithUnitName.append(data.get(i).getBusinessUnitName());
                            } else {
                                doctorNameWithUnitName.append(data.get(i).getBusinessUnitName() + ",");
                            }
                        }
                        consumer.setDoctorNameWithUnitName(doctorNameWithUnitName.toString());
                    });
                dtDefineSpaceVo.setDtDefineSpaceConsumerList(dtDefineSpaceConsumerVos);
            }
            buildListSuccess(lr, dtDefineSpaceVo);
        }

        } catch (Exception e) {
            log.error("获取单个定义空间发送异常", e);
            buildListWarn(lr, "获取单个定义空间失败");
        }
        return lr;
    }

    @Override
    public ActionResult checkName(String name, Long defineSpaceSoid) {
        return dtDefineSpaceApi.checkName(name, defineSpaceSoid);
    }

    @Override
    public ListResult<PageResultVo<DtDefineSpaceVo>> findPage(String searChData, Long currentPage, Long pageSize) {
        ListResult<DtDefineSpaceVo> lr = new ListResult<DtDefineSpaceVo>();
        ListResult<PageResultVo<DtDefineSpaceVo>> page = null;
        try {
            page = dtDefineSpaceApi.findPage(searChData, currentPage, pageSize);
            if (ObjectUtils.isNotEmpty(page) && ObjectUtils.isNotEmpty(page.getData())) {
                PageResultVo<DtDefineSpaceVo> data = page.getData();
                if (ObjectUtils.isNotEmpty(data) && CollectionUtils.isNotEmpty(data.getList())) {
                    List<DtDefineSpaceVo> list = data.getList();
                    List<DtDefineSpaceVo> dtDefineSpaceList = list.stream().filter(dtDefineSpace -> ObjectUtils.isNotEmpty(dtDefineSpace) && ObjectUtils.isNotEmpty(dtDefineSpace.getStatus())).map(
                            defineSpace -> {
                                DtDefineSpaceVo dtDefineSpaceVo = new DtDefineSpaceVo();
                                BeanUtils.copyProperties(defineSpace, dtDefineSpaceVo);
                                Long status = defineSpace.getStatus();
                                //string STATUSNAME
                                MsdDataSet conceptSoidByDataSetSoid = detailCodingSystemService.getConceptSoidByDataSetSoid(status);
                                if (ObjectUtils.isNotEmpty(conceptSoidByDataSetSoid) && StringUtils.isNotBlank(conceptSoidByDataSetSoid.getDataSetMeaning())) {
                                    dtDefineSpaceVo.setStatusName(conceptSoidByDataSetSoid.getDataSetMeaning());
                                }
                                return dtDefineSpaceVo;
                            }
                    ).collect(Collectors.toList());
                    data.setList(dtDefineSpaceList);
                }
            }
        } catch (Exception e) {
            log.error("分页查命名体系发送异常", e);
            buildListWarn(lr, "分页查命名体系发送异常");
        }
        return page;
    }

    @Override
    public ActionResult updateStatus(Long status, Long defineSpaceSoid) {
        return dtDefineSpaceApi.updateStatus(status, defineSpaceSoid);
    }

    @Override
    public ListResult<List<DtDefineSpace>> findAll(String searchData) {
        return dtDefineSpaceApi.findAll(searchData);
    }

    @Override
    public ListResult<List<DtDefineSpaceConsumerVo>> findListByOrgSoid(Long orgInfoSoid, Long orgInfoType, String search) {
        log.info("查询条件:1." + orgInfoSoid + "2." + search);
        ListResult result = new ListResult();
        StopWatch st = StopWatch.createStarted();
        List<DtDefineSpaceConsumerVo> list = null;
        DtDefineSpaceConsumerVo dtDefineSpaceConsumerVo = null;
        try {
            ListResult<List<EmployeeInfoVo>> listTmp = mdmService.findListByOrgSoid(orgInfoSoid, orgInfoType, search);
            if (listTmp != null && listTmp.getData() != null
                    && listTmp.getData().size() > 0) {
                List<EmployeeInfoVo> listEmployeeInfoVo = listTmp.getData();
                list = new ArrayList<DtDefineSpaceConsumerVo>();
                for (EmployeeInfoVo vo : listEmployeeInfoVo) {
                    String doctorName = vo.getEmployeeName();
                    ListResult<List<BusinessUnitVo>> unitList =
                            mdmService.findBusinessUnitListByEmployeeSoid(vo.getEmployeeSoid(), null);
                    StringBuffer doctorNameWithUnitName = new StringBuffer(doctorName + "|");
                    List<BusinessUnitVo> data = unitList.getData();
                    for (int i = 0; i < data.size(); i++) {
                        if (i == data.size() - 1) {
                            doctorNameWithUnitName.append(data.get(i).getBusinessUnitName());
                        } else {
                            doctorNameWithUnitName.append(data.get(i).getBusinessUnitName() + ",");
                        }
                    }
                    dtDefineSpaceConsumerVo = new DtDefineSpaceConsumerVo();
                    dtDefineSpaceConsumerVo.setDoctorNameWithUnitName(doctorNameWithUnitName.toString());
                    dtDefineSpaceConsumerVo.setDoctorSoid(vo.getEmployeeSoid());
                    list.add(dtDefineSpaceConsumerVo);
                }

            }
            buildListSuccess(result, list);
        } catch (Exception e) {
            log.error("根据医院soid模糊查询当前医院下员工信息异常" + e.getMessage(), e);
            buildListWarn(result, "根据医院soid模糊查询当前医院下员工信息失败");
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");
        }
        return result;
    }

    @Override
    public ListResult<List<BaseOrgInfoVo>> findHospitalByEmployeeSoid(HttpServletRequest request) {
        ListResult<List<BaseOrgInfoVo>> list = new ListResult<>();
        try {
            ListResult<UserDto> loginUserInfo = mdmService.getLoginUserInfo();
            UserDto loginUser = loginUserInfo.getData();
            Long employeeSoid = loginUser.getEmployeeSoid();

            if (loginUser == null) {
                list.setData(new ArrayList<BaseOrgInfoVo>());
                list.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                list.setMessage("根据当前用户员工标识,未查询到相关医院");
                return list;
            }
            employeeSoid = loginUser.getEmployeeSoid();
            list=mdmService.findHospitalByEmployeeSoid(employeeSoid);
            return list;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            List<BaseOrgInfoVo> listTmp = new ArrayList<BaseOrgInfoVo>();
            listTmp.add(new BaseOrgInfoVo());
            list.setData(listTmp);
            list.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            list.setMessage("根据当前用户员工soid查询医院处理失败");
            return list;
        }
    }
}
